<template>
  <div>
    <div>
      <el-button
        type="primary"
        size="default"
        @click="
          startNewInstance({
            filePath: 'Z:\\CyberModel\\sample\\Architectural.cdb',
            fileId: '1948290060980793346',
            userName: 'Jack8',
            fawkesAuthToken:
              'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRJZCI6ImZhd2tlcyIsInVzZXJfbmFtZSI6IkphY2s4Iiwic2V4IjoiIiwidXNlck5vIjoiVTIwMTkwMDQiLCJ1c2VyTmFtZSI6IkphY2s4IiwiY2xpZW50X2lkIjoiZmF3a2VzIiwiYXZhdGFyVG9rZW4iOm51bGwsImxpY2Vuc2UiOiJwb3dlcmVkIGJ5IGZhd2tlcyIsImF1ZCI6WyJvYXV0aDItcmVzb3VyY2UiLCJvYXV0aDItc2VydmVyIl0sInBob25lIjoiIiwic2NvcGUiOlsiYWxsIl0sInRlbmFudElkIjoxMDAwMDAsInVzZXJGdWxsbmFtZSI6IkphY2siLCJpZCI6IjEyMDcxODA1ODk0ODU4OTU2ODEiLCJ1c2VyVHlwZSI6MSwiZXhwIjoxNzU1OTEzNzQyLCJqdGkiOiI2ZTMyYzRkYy0wNjNjLTQ4ZGYtYTI4YS0xMThlNDU0MTE5MmUiLCJlbWFpbCI6IiJ9.72xFtmW-IPpP_f-ptCHj4vKtXfUEFB0rdJhWwXzCkCw',
          })
        "
        plain
        class="light-blue-button"
      >
        创建实例
      </el-button>

      <el-button
        type="warning"
        size="default"
        @click="stressTest"
        plain
        class="light-blue-button"
        style="margin-left: 10px"
      >
        压力测试
      </el-button>
    </div>

    <el-card v-if="newInstanceInfo" style="margin-top: 20px">
      <template #header>
        <span>新创建实例</span>
      </template>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="实例ID">{{ newInstanceInfo.id }}</el-descriptions-item>
        <el-descriptions-item label="服务器地址">{{
          newInstanceInfo.serverUrl
        }}</el-descriptions-item>
        <el-descriptions-item label="云渲染地址">
          <el-space>
            {{ newInstanceInfo.streamUrl }}
            <el-button
              type="primary"
              size="default"
              @click="openStream(newInstanceInfo.streamUrl)"
              plain
              class="light-blue-button"
            >
              进入云渲染页面
            </el-button>
          </el-space>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-row>
      <el-button
        type="primary"
        size="default"
        @click="refreshServersLoads"
        plain
        class="light-blue-button"
      >
        刷新节点负载
      </el-button>

      <el-button
        type="primary"
        size="default"
        @click="refreshServersStatus"
        plain
        class="light-blue-button"
      >
        刷新节点实例数量
      </el-button>

      <el-button
        type="primary"
        size="default"
        @click="stopAllInstances"
        plain
        class="light-blue-button"
      >
        停止所有服务器上的实例
      </el-button>
    </el-row>

    <el-table :data="serverLoads" style="width: 100%; margin-bottom: 20px" border>
      <el-table-column prop="serverUrl" label="服务器地址" width="180" />
      <el-table-column prop="runningInstances" label="活跃实例数" width="100" />
      <el-table-column prop="pendingInstances" label="待启动实例数" width="120" />
      <el-table-column prop="maxInstances" label="最大实例数" width="100" />
      <el-table-column prop="cpuLoad" label="CPU使用率(%)" width="120" />
      <el-table-column prop="memUsage" label="内存使用率(%)" width="120" />
      <el-table-column label="操作" width="430">
        <template #default="{ row }">
          <el-row justify="start" class="nowrap">
            <el-button
              type="primary"
              size="default"
              @click="showInstances(row.serverUrl)"
              plain
              class="light-blue-button"
            >
              查看实例信息
            </el-button>

            <el-button
              v-if="debug"
              type="primary"
              size="default"
              @click="openAvailableStreamOnServer(row.serverUrl)"
              plain
              class="light-blue-button"
            >
              访问可用的视频流
            </el-button>

            <el-button
              type="primary"
              size="default"
              @click="stopAllInstancesOnServer(row.serverUrl)"
              plain
              class="light-blue-button"
            >
              停止所有实例
            </el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="instances.length">
      <h3>实例列表（{{ currentServerUrl }}）</h3>
      <el-table :data="instances" style="width: 100%; margin-bottom: 20px" border>
        <el-table-column prop="id" label="实例ID" width="180" />
        <el-table-column prop="status" label="状态" width="120" />
        <el-table-column prop="streamUrl" label="云渲染地址" />
        <el-table-column prop="createdTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="default"
              @click="stopOne(row.id)"
              plain
              class="light-blue-button"
            >
              停止
            </el-button>

            <el-button
              type="primary"
              size="default"
              @click="openStream(row.streamUrl)"
              plain
              class="light-blue-button"
            >
              进入云渲染页面
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { dispatcher } from '../api/dispatcher';

const debug = ref<boolean>(false); // 是否开启调试模式
const serverLoads = ref<any[]>([]);
const instances = ref<any[]>([]);
const currentServerUrl = ref('');
const newInstanceInfo = ref<any | null>(null); // 用于存储新创建的实例信息

function delay(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function startNewInstance(
  para: { filePath?: string; fileId?: string; userName?: string; fawkesAuthToken?: string } = {},
) {
  try {
    const { data } = await dispatcher.startInstance(para);
    // console.log(data)

    if (data && !data.error) {
      newInstanceInfo.value = {
        id: data.id,
        serverUrl: data.serverUrl,
        streamUrl: data.streamUrl,
      };
      await refreshServersStatus();
      if (currentServerUrl.value === data.serverUrl) {
        await showInstances(currentServerUrl.value);
      }
    } else {
      newInstanceInfo.value = null;
      alert('创建实例失败: ' + (data.error || '未知错误'));
    }
    return data;
  } catch (error) {
    newInstanceInfo.value = null;
    if (error instanceof Error) {
      return { error: error.message || '网络错误' };
    } else {
      return { error: '未知错误' };
    }
  }
}

async function stressTest() {
  const promises = Array.from({ length: 40 }, () =>
    startNewInstance({
      filePath: 'Z:\\CyberModel\\sample\\Architectural.cdb',
      fileId: '1948290060980793346',
      userName: 'Jack8',
      fawkesAuthToken:
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRJZCI6ImZhd2tlcyIsInVzZXJfbmFtZSI6IkphY2s4Iiwic2V4IjoiIiwidXNlck5vIjoiVTIwMTkwMDQiLCJ1c2VyTmFtZSI6IkphY2s4IiwiY2xpZW50X2lkIjoiZmF3a2VzIiwiYXZhdGFyVG9rZW4iOm51bGwsImxpY2Vuc2UiOiJwb3dlcmVkIGJ5IGZhd2tlcyIsImF1ZCI6WyJvYXV0aDItcmVzb3VyY2UiLCJvYXV0aDItc2VydmVyIl0sInBob25lIjoiIiwic2NvcGUiOlsiYWxsIl0sInRlbmFudElkIjoxMDAwMDAsInVzZXJGdWxsbmFtZSI6IkphY2siLCJpZCI6IjEyMDcxODA1ODk0ODU4OTU2ODEiLCJ1c2VyVHlwZSI6MSwiZXhwIjoxNzU1OTEzNzQyLCJqdGkiOiI2ZTMyYzRkYy0wNjNjLTQ4ZGYtYTI4YS0xMThlNDU0MTE5MmUiLCJlbWFpbCI6IiJ9.72xFtmW-IPpP_f-ptCHj4vKtXfUEFB0rdJhWwXzCkCw',
    }).catch((error) => ({ error: error.message || '创建实例失败' })),
  );
  const results = await Promise.all(promises);
  const successCount = results.filter((result) => !result.error).length;
  const failCount = results.length - successCount;
  console.log(`成功创建${successCount}个实例，失败${failCount}个实例`);
}

// async function stressTest() {
//   for (let i = 0; i < 5; i++) {
//     startNewInstance({
//       filePath: 'Z:\\CyberModel\\sample\\Architectural.cdb',
//       fileId: '1948290060980793346',
//       userName: 'Jack8',
//       fawkesAuthToken:
//         'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRJZCI6ImZhd2tlcyIsInVzZXJfbmFtZSI6IkphY2s4Iiwic2V4IjoiIiwidXNlck5vIjoiVTIwMTkwMDQiLCJ1c2VyTmFtZSI6IkphY2s4IiwiY2xpZW50X2lkIjoiZmF3a2VzIiwiYXZhdGFyVG9rZW4iOm51bGwsImxpY2Vuc2UiOiJwb3dlcmVkIGJ5IGZhd2tlcyIsImF1ZCI6WyJvYXV0aDItcmVzb3VyY2UiLCJvYXV0aDItc2VydmVyIl0sInBob25lIjoiIiwic2NvcGUiOlsiYWxsIl0sInRlbmFudElkIjoxMDAwMDAsInVzZXJGdWxsbmFtZSI6IkphY2siLCJpZCI6IjEyMDcxODA1ODk0ODU4OTU2ODEiLCJ1c2VyVHlwZSI6MSwiZXhwIjoxNzU1OTEzNzQyLCJqdGkiOiI2ZTMyYzRkYy0wNjNjLTQ4ZGYtYTI4YS0xMThlNDU0MTE5MmUiLCJlbWFpbCI6IiJ9.72xFtmW-IPpP_f-ptCHj4vKtXfUEFB0rdJhWwXzCkCw',
//     });
//   }
// }

function openUrlInNewWindow(streamUrl: string) {
  if (streamUrl) {
    window.open(streamUrl, '_blank');
  } else {
    alert('无效的地址');
  }
}

function openStream(url: string) {
  const params = `?streamUrl=${url}&mode=ueCloud`;
  const newUrl = 'http://172.20.64.68:56789/cloud/' + params;
  openUrlInNewWindow(newUrl);
}

function openAvailableStreamOnServer(url: string) {
  const newUrl = url + '?HoveringMouse=true';
  openUrlInNewWindow(newUrl);
}

async function refreshServersLoads() {
  try {
    const { data } = await dispatcher.getServersLoads();
    serverLoads.value = data;
  } catch (error) {
    console.error('刷新节点负载失败: ', error);
  }
}

async function refreshServersStatus() {
  try {
    const { data } = await dispatcher.getServersStatus();
    serverLoads.value = serverLoads.value.map((existingServer) => {
      const updatedServer = data.find(
        (newServer) => newServer.serverUrl === existingServer.serverUrl,
      );
      if (updatedServer) {
        return {
          ...existingServer,
          runningInstances: updatedServer.runningInstances,
          pendingInstances: updatedServer.pendingInstances,
          maxInstances: updatedServer.maxInstances,
        };
      }
      return existingServer;
    });
  } catch (error) {
    console.error('刷新节点状态失败: ', error);
  }
}

async function showInstances(serverUrl: string) {
  currentServerUrl.value = serverUrl;
  const { data } = await dispatcher.getInstances(serverUrl);
  instances.value = data.instances || data || [];
}

async function stopOne(instanceId: string) {
  await dispatcher.stopInstance(currentServerUrl.value, instanceId);
  await delay(1000);
  await showInstances(currentServerUrl.value);
  await refreshServersStatus();
}

async function stopAllInstances() {
  await dispatcher.stopAllInstances();
  await delay(1000);
  await refreshServersStatus();
  instances.value = [];
}

async function stopAllInstancesOnServer(serverUrl: string) {
  await dispatcher.stopAllInstancesOnServer(serverUrl);
  await delay(1000);
  await showInstances(serverUrl);
  await refreshServersStatus();
}

refreshServersLoads(); //组件创建时立即执行一次
</script>

<style scoped>
.light-blue-button {
  border-color: #87cefa; /* 边框颜色 */
  color: #1e90ff; /* 文字颜色 */
  background-color: #e0f6ff;
  transition: all 0.3s ease; /* 过渡效果 */
}

.light-blue-button:hover {
  background-color: #b0e0e6; /* 鼠标悬停时加深背景色 */
  border-color: #1e90ff; /* 鼠标悬停时加深边框色 */
  color: white; /* 鼠标悬停时文字变白 */
}

.nowrap {
  flex-wrap: nowrap;
}
</style>
